﻿using System.Collections.Specialized;
using System.Net;

namespace LinkedInApi
{
    partial class ApiClient
    {
        private class ApiWebClient : WebClient
        {
            System.Timers.Timer timeoutTimer;

            public ApiWebClient(AccessToken accessToken = null)
                : base()
            {
                this.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                this.Headers["x-li-format"] = "json";
                this.Headers[HttpRequestHeader.AcceptEncoding] = this.Headers[HttpRequestHeader.ContentEncoding] = "UTF-8";

                if (accessToken != null)
                    this.Headers["Authorization"] = "Bearer " + accessToken.Token;

                this.Encoding = System.Text.Encoding.UTF8;
                this.Proxy = null;
            }

            public System.Threading.Tasks.Task<byte[]> DownloadDataTaskAsync(string address, int timeout)
            {
                if (this.timeoutTimer != null)
                    return null;

                this.timeoutTimer = new System.Timers.Timer() { Interval = timeout, AutoReset = false, Enabled = false };
                this.timeoutTimer.Elapsed += ((sender, args) =>
                {
                    this.CancelAsync();
                    this.timeoutTimer = null;
                });

                this.timeoutTimer.Start();
                return this.DownloadDataTaskAsync(address);
            }

            public System.Threading.Tasks.Task<byte[]> UploadValuesTaskAsync(string address, NameValueCollection data, int timeout)
            {
                if (this.timeoutTimer != null)
                    return null;

                this.timeoutTimer = new System.Timers.Timer() { Interval = timeout, AutoReset = false, Enabled = false };
                this.timeoutTimer.Elapsed += ((sender, args) =>
                {
                    this.CancelAsync();
                    this.timeoutTimer = null;
                });

                this.timeoutTimer.Start();
                return this.UploadValuesTaskAsync(address, data);
            }

            protected override void Dispose(bool disposing)
            {
                if (this.timeoutTimer != null)
                {
                    this.timeoutTimer.Stop();
                    this.timeoutTimer = null;
                }

                base.Dispose(disposing);
            }
        }
    }
}
